package com.sunchangming.stmdb.xgen;

import java.nio.file.Path;
import java.util.ArrayList;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.thoughtworks.xstream.XStream;

public class StmdbConfig {
	private final static Logger logger = LoggerFactory.getLogger(StmdbConfig.class);

	public static XStream getXStream() {
		final XStream xstream = new XStream(new DomDriver());
		xstream.autodetectAnnotations(true);
		xstream.alias("stmdb", StmdbConfig.class);
		xstream.registerConverter(new BeanConverter());
		xstream.registerConverter(new StmdbConverter());
		xstream.registerConverter(new MyEnumConverter());
		return xstream;
	}

	ArrayList<Bean> beans = new ArrayList<Bean>();
	ArrayList<Enum> enums = new ArrayList<Enum>();
	ArrayList<Table> tables = new ArrayList<Table>();
	int serverid;

	/**
	 * 所有的自定义类型放在哪个namespace下
	 * 
	 * @return
	 */
	public String getFullName() {
		return "mybeans";
	}

	public void types() {
		for (final Bean b : this.beans) {
			final TypeBean tb = new TypeBean(b, false);
			Types.getInstance().add(tb.getFullName(), tb);
		}

		for (final Enum b : this.enums) {
			final TypeBean tb = new TypeBean(b, true);
			Types.getInstance().add(tb.getFullName(), tb);
		}
	}

	public void compile() {
		for (final Bean b : this.beans) {
			b.compile();
		}
	}

	public void generateCode(Path src, String language) throws Exception {
		final Path p = getDir(src);
		if (!java.nio.file.Files.exists(p))
			java.nio.file.Files.createDirectories(p);
		if (!java.nio.file.Files.exists(p)) {
			logger.error("output dir doesn't exists");
			return;
		}

		for (final Bean bean : beans) {
			bean.generateCode(src, language);
		}
		for (final Enum e : enums) {
			e.generateCode(src, language);
		}

	}

	public Path getDir(Path topSourceDir) {
		return topSourceDir.resolve("mybeans");
	}
}
